/*
 * @ author madman 
 * @ use 后台菜单权限业务
 */
const PermissionsModel = require('../../models/system/permissions.model');
const Utils = require('../utils');
function stripscript(str) { 
    var pattern = new RegExp("[|—]") 
    var rs = ""; 
    for (var i = 0; i < str.length; i++) { 
        var _str = str.substr(i, 1)
        rs = rs + str.substr(i, 1).replace(pattern, ''); 
    } 
    return rs; 
}

const getTree =  function(arr, pid, isTree = false){
    const _mapArr = []
    arr.map((item, key) => {
      if (item.level !== '3') {
          if (item.parentId !== pid) {
            if(item.name.indexOf('|—') < 1 && item.level !== '3'){
                item.name = '|—' +  item.name
            }else{
                item.name = '|——' +  item.name
            }
          }
          _mapArr.push(item)
       }
    })
    return _mapArr
}
const getTreeChinden =  function(arr, pid){
    return arr.map((item, key) => {
        if (item.parentId === pid) {
            return item
        } 
    })
}
class AdminPermissionController {
    //递归分类树
    static getTree(arr, pid, type) {
        const _mapArr = []
        arr.map((item, key) => {
            if (item.parentId === pid) {
                const options = !type ? { 
                   '_id': item._id,
                   'parentId': item.parentId,
                   'name': item.name,
                   'level': item.level,
                   'icon': item.icon,
                   'isMenu': item.isMenu,
                   'routerUrl': item.routerUrl,
                   'routerName': item.routerName,
                   'routerParameter': item.routerParameter,
                   'isChild': item.isChild,
                   'sort': item.sort,
                   'routerParameterDescribe': item.routerParameterDescribe,
                   'routerDescribe': item.routerDescribe 
                } : {
                   '_id': item._id,
                   'name': item.name, 
                }
                const _arrs = AdminPermissionController.getTree(arr, item._id, type)
                if (_arrs.length > 0) {
                    options.children = _arrs
                }
                _mapArr.push(options)
            }
        })
        return _mapArr
    }
    // 添加权限菜单
    async add(ctx) {
        const _body = ctx.request.body
        const _userId = ctx.cookies.get('user_id')
        const _params = Utils._params(_body)
        const result = await PermissionsModel.create(_params);
        if (result) {
            return ctx.success({ msg: '添加成功' });
        } else {
            return ctx.error({ msg: '添加失败' });
        }
    }
    // 更新权限菜单
    async update(ctx) {
        const _body = ctx.request.body
        const _params = Utils._params(_body)
        _params.updataAt = new Date()
        _params.name = stripscript(_params.name)
        const result = await PermissionsModel.update({ _id: _body._id }, { $set: _params });
        if (result) {
            return ctx.success({ msg: '更新成功' });
        } else {
            return ctx.error({ msg: '更新失败' });
        }
    }

    // 删除权限菜单
    async delete(ctx) {
        const _id = ctx.query.id
        const _userId = ctx.cookies.get('user_id')
        const result = await PermissionsModel.remove({ _id: _id });
        await RolesModel.update({ _id: _userId }, { $pull: {power:{ $in: [ _id ] } } }); //删除权限
        if (result) {
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }
    /*
     * 批量删除方法
     */
    async batchdelete(ctx, name) {
        const arrids = ctx.request.body.arrids
        let result = await PermissionsModel.remove({ _id: { $in: arrids } })
        if (result) {
            return ctx.success({ msg: '删除成功' });
        } else {
            return ctx.error({ msg: '删除失败' });
        }
    }
    // 获取带分页权限列表
    async list(ctx) {
        const options = {
            name: 'system/permissions',
            sortType: 'sort',
            sortVal: '1'
        }
        if (ctx.query.page) {
            // options.type = 'page'
        } else {
            //过滤显示字段，优化性能
            options.queryField = {
                // parentId: 0,
                icon: 0,
                sort: 0,
                isMenu: 0,
                isChild: 0,
                routerDescribe: 0,
                routerName: 0,
                routerParameter: 0,
                routerParameterDescribe: 0,
                routerUrl: 0
            }
        }
        let result = await Utils.getPageList(ctx, options)
        if(ctx.query._type === '1') {
           result.result = getTree(result.result, '-1')  //排序添加子分类
        }else{
           result.result = AdminPermissionController.getTree(result.result, '-1')
        }
        if (result) {
            return ctx.success({
                data: result,
                msg: '查询成功'
            });
        }
    }

}

export default new AdminPermissionController;